import { createStore } from 'vuex'
import axios from 'axios'

const apiClient = axios.create({
  baseURL: 'http://localhost:5000/api',
  withCredentials: false,
  // withCredentials: 这个选项决定了是否在跨域请求中发送凭据（如 cookies、HTTP 认证信息等）。
  // 默认值是 false，表示不发送凭据。
  headers: {
    Accept: 'application/json', //客户端期望接收 JSON 格式的数据。
    'Content-Type': 'application/json', //这个头告诉服务器，客户端发送的数据是 JSON 格式的
  },
})

// vuex用法
export default createStore({
  state: {
    students: [],
    token: localStorage.getItem('token') || null,
  },
  mutations: {
    setStudents(state, students) {
      state.students = students
    },
    setToken(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    clearToken(state) {
      state.token = null
      localStorage.removeItem('token')
    },
    addStudent(state, student) {
      state.students.push(student)
    },
    removeStudent(state, id) {
      state.students = state.students.filter((student) => student.id !== id)
    },
    updateStudent(state, updatedStudent) {
      state.students = state.students.map((student) =>
        student.id === updatedStudent.id ? updatedStudent : student,
      )
    },
  },
  actions: {
    // 获取学生信息数据
    async fetchStudents({ commit, state }) {
      try {
        const response = await apiClient.get('/students', {
          headers: {
            Authorization: `Bearer ${state.token}`,
          },
        })
        commit('setStudents', response.data)
      } catch (error) {
        console.error('There was an error fetching the students!', error)
      }
    },
    // 登录逻辑
    async login({ commit }, { username, password }) {
      try {
        const response = await apiClient.post('/login', { username, password })
        // 将登录成功得到的token存储在本地
        commit('setToken', response.data.token)
      } catch (error) {
        console.error('Login failed!', error)
        throw error // 重新抛出错误，以便在组件中捕获
      }
    },
    // 退出登录
    logout({ commit }) {
      console.log('退出了')
      commit('clearToken')
    },
    // 添加学生
    addStudent({ commit, state }, newStudent) {
      return apiClient
        .post('/students', newStudent, {
          headers: {
            Authorization: `Bearer ${state.token}`,
          },
        })
        .then((response) => {
          commit('addStudent', response.data)
        })
    },
    // 编辑/更新学生
    updateStudent({ commit, state }, updatedStudent) {
      return apiClient
        .put(`/students/${updatedStudent.id}`, updatedStudent, {
          headers: {
            Authorization: `Bearer ${state.token}`,
          },
        })
        .then(() => {
          commit('updateStudent', updatedStudent)
        })
    },
    // 删除学生信息
    deleteStudent({ commit, state }, id) {
      return apiClient
        .delete(`/students/${id}`, {
          headers: {
            Authorization: `Bearer ${state.token}`,
          },
        })
        .then(() => {
          commit('removeStudent', id)
        })
    },
  },
  getters: {
    getStudents: (state) => state.students,
    isLoggedIn: (state) => !!state.token,
  },
})
